<script setup>
import { onMounted, nextTick, computed } from "vue"
import Viewer from 'viewerjs'
import "viewerjs/dist/viewer.css"

const props = defineProps(["noteImgs"])
const viewer = ref(null)
const viewerDom = ref(null); // 用于装载用ref属性获取的Dom
const rawBtuDom = ref(null) // 查看原图按钮的Dom
const rawImgIndexs = ref([]) // 存储了哪些图片需要原图的index

// 1句话，让viewer为我打工
onMounted(() => {

  viewer.value = new Viewer(viewerDom.value, {
    button: false, //右上角关闭按钮
    shown: () => { // 大图展示时，加入查看原图按钮
      let viewerDom = document.querySelector('#viewer' + viewer.value.id + '>.viewer-footer>.viewer-toolbar>ul')
      viewerDom.appendChild(rawBtuDom.value)
    },
  })

});

// 加载不出来图片，重试3次，用于阿里云刚刚才存储图片，这边就开始访问
const handleError = (event) => {
  let errortime = event.target.attributes.errortime;
  errortime.value < 3 ? setTimeout(() => { event.target.src = event.target.src; errortime.value++ }, 1000) : 0;
}

const imgs = computed(() => {
  let aImgs = []
  for (const i in props.noteImgs) {
    if (rawImgIndexs.value.indexOf(+i) < 0) {
      aImgs.push(BucketURL + '/compress-imgs/' + props.noteImgs[i])
    } else {
      aImgs.push(BucketURL + '/note-imgs/' + props.noteImgs[i])
    }
  }
  return aImgs
})

// 点击加载原图
const loadRawImg = () => {
  let i = viewer.value.index
  if (rawImgIndexs.value.indexOf(i) < 0) {
    rawImgIndexs.value.push(i)
    nextTick(() => viewer.value.update().view(i))
  }
}
</script>

<template>
  <!-- @scroll.passive.once="handleClick" -->
  <div class="imgs viewer" id="viewer" ref="viewerDom">
    <img v-for="img in imgs" :key="img" :src="img" errortime=0 :onerror="handleError" />
  </div>

  <div v-show="false">
    <li ref="rawBtuDom" @click="loadRawImg" style="color:#fff;font-size: 15px;border-radius:12px;width:80px;line-height: 24px;">
      查看原图
    </li>
  </div>
</template>

<style scoped lang="less">
.imgs {
  // border: 1px solid red;
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow-x: auto;

  img {
    border: 1px solid var(--model-border-color);
    border-radius: 5px;
    object-fit: cover;
    height: 90px;
    width: 90px;
    margin-right: 1px;
  }
}
</style>